package cn.com.haopy.yue.ai.admin.web;


import cn.com.haopy.yue.ai.admin.utils.AdminResponseCode;
import cn.com.haopy.yue.ai.core.component.SecurityComponent;
import cn.com.haopy.yue.ai.core.system.SystemConfig;
import cn.com.haopy.yue.ai.core.utils.AESUtil;
import cn.com.haopy.yue.ai.core.utils.JacksonUtil;
import cn.com.haopy.yue.ai.core.utils.ResponseUtil;
import cn.com.haopy.yue.ai.core.utils.bcrypt.BCryptPasswordEncoder;
import cn.com.haopy.yue.ai.db.entity.arisk.HOSAdmin;
import cn.com.haopy.yue.ai.db.service.hos.HOSAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/admin/profile")
@Validated
@Api(tags = "个人配置相关")
public class AdminProfileController {
    private final Log logger = LogFactory.getLog(AdminProfileController.class);

    @Autowired
    private HOSAdminService adminService;


    @Autowired
    private SecurityComponent securityComponent;

    @RequiresAuthentication
    @PostMapping("/password")
    @ApiOperation(value = "修改密码")
    public Object create(@RequestBody String body) {
        return updatePassword(body);
    }

    @RequiresAuthentication
    @PostMapping("/passwordByEncrypted")
    @ApiOperation(value = "修改密码(加密方式)", httpMethod = "POST")
    public Object createByEncrypted(@RequestBody
                                    @ApiParam("{ cipher: JSON对象\"{oldPassword: xxx, newPassword: xxx}\"转为字符串后经AES加密后的BASE64字符串}")
                                    String body) {
        String cipher = JacksonUtil.parseString(body, "cipher");
        String key = SystemConfig.getSystemIntfcSecretAesKey();
        String decryptedBody;
        try {
            decryptedBody = AESUtil.decrypt(cipher, key);
        } catch (Exception e) {
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT, "修改失败，数据错误");
        }

        return updatePassword(decryptedBody);
    }

    private Object updatePassword(String body) {
        String oldPassword = JacksonUtil.parseString(body, "oldPassword");
        String newPassword = JacksonUtil.parseString(body, "newPassword");

        if (StringUtils.isEmpty(oldPassword)) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isEmpty(newPassword)) {
            return ResponseUtil.badArgument();
        }

        try {
            securityComponent.checkPasswordComplexity(newPassword);
        } catch (Exception ex) {
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_PASSWORD, ex.getMessage());
        }

        Subject currentUser = SecurityUtils.getSubject();
        HOSAdmin admin = (HOSAdmin) currentUser.getPrincipal();

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(oldPassword, admin.getPassword())) {
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT, "账号密码不对");
        }

        String encodedNewPassword = encoder.encode(newPassword);
        admin.setPassword(encodedNewPassword);
        admin.setLastChangePasswordTime(LocalDateTime.now());

        adminService.updateById(admin);
        return ResponseUtil.ok();
    }


}
